<?php
class CacheMem{
	private  $connect;
	private  $config;
	private static $instance;

	public static function create(){
		if (!isset(self::$instance)) {
			$c = __CLASS__;
			self::$instance = new $c;
		}
		return self::$instance;
	}

	private function __construct(){
		$this->config = YYK::$config['cacheMem'];
		self::server(0);
	}

	public function server($n=0){
		if (isset($this->config[$n]) && is_array($this->config[$n])) {
			
		}
		else{
			return false;
		}
		if (is_object($this->connect)) {
			$this->connect->quit();
		}
		$this->connect = new Memcached;
		$this->connect->setOption(Memcached::OPT_COMPRESSION, false);
		$this->connect->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
		$this->connect->addServer($this->config[$n]['host'], $this->config[$n]['port']);
		if (isset($this->config[$n]['username']) && isset($this->config[$n]['password']) && strlen($this->config[$n]['username'])>0 ) {
			$this->connect->setSaslAuthData($this->config[$n]['username'], $this->config[$n]['password']) ;
		}

		return self::$instance;
	}

	public function set($key, $value, $expire=0){
		$result = $this->connect->set($key, $value, $expire) ;
		//var_dump(self::$connect->getResultCode());
		return $result;
	}

	public function get($key){
		//var_dump(self::$connect->get($key));
		if (($value = $this->connect->get($key) )== Memcached::RES_NOTFOUND) {
			return false;
		}
		else{
			return $value;
		}
		
	}
	
	public function getAllKeys(){
		return $this->connect->getAllKeys();
	}

	public function __destruct(){
		$this->connect->quit();
	}
}